package com.ufida.ids.servlet;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.hereway.core.exception.ServiceException;
import com.hereway.core.servlet.BaseServlet;
import com.hereway.core.util.ParamUtils;
import com.ufida.ids.model.AppModel;
import com.ufida.ids.service.IAppService;
import com.ufida.ids.util.Constants;
import com.ufida.ids.util.Dom4jUtil;
import com.ufida.ids.util.ExtUtil;
import com.ufida.ids.util.StringUtil;

public class AppRegisterServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
	
	private static Logger logger = Logger.getLogger(AppRegisterServlet.class);

	@Autowired
	private IAppService appService;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AppRegisterServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		//获取操作类型
		String action = ParamUtils.getParameter(request, "action");
		logger.debug("action:"+action);
		if ("getAppRegisterListByCon".equals(action)){//获取列表
			getAppRegisterListByCon(request, response);
		}else if("add".equals(action)){//新增
			add(request, response);
		}else if("active".equals(action)){//启用
			active(request, response);
		}else if("unactive".equals(action)){//停用
			unactive(request, response);
		}else if("delete".equals(action)){//删除
			delete(request, response);
		}else if("getAppRegisterextFieldinfo".equals(action)){//获取其它属性字符串
			getAppRegisterextFieldinfo(request, response);
		}else if("edit".equals(action)){
			edit(request, response);
		}
	}
	
	private void getAppRegisterListByCon(HttpServletRequest request, HttpServletResponse response) {
		int pageNum = Integer.parseInt(request.getParameter("page"));	
		String condition = request.getParameter("condition");
		JSONObject o = JSONObject.fromObject(condition);
		String appName =  o.optString("appName");
		String url =  o.optString("url");
		try {
			String retStr = appService.getAppListByConPagging(appName, url, pageNum);
			writeResponse(response, retStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void getAppRegisterextFieldinfo(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		String retStr = "";
		try {
			AppModel app = appService.get(Long.parseLong(id));
			System.out.println("extFieldinfo:"+app.getExtFieldinfo());
			if(null != app.getExtFieldinfo() && !"".equals(app.getExtFieldinfo())){
				retStr = Dom4jUtil.getJSON(app.getExtFieldinfo());
			}
			writeResponse(response, retStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void add(HttpServletRequest request, HttpServletResponse response) {
		logger.debug("[add appRegister...]");
		boolean flag = true;
		String retStr = "";
		try{
			AppModel appModel = buildAppRegister(request,"add");
			appService.save(appModel);
		} catch (Exception e) {
			e.printStackTrace();
			flag = false;
		}
		retStr = ExtUtil.getJosonStr(flag);
		
		writeResponse(response, retStr);
	}
	
	private void edit(HttpServletRequest request, HttpServletResponse response) {
		logger.debug("[edit appRegister...]");
		boolean flag = true;
		String retStr = "";
		try{
			AppModel appModel = buildAppRegister(request, "edit");
			appService.update(appModel);
		} catch (Exception e) {
			e.printStackTrace();
			flag = false;
		}
		retStr = ExtUtil.getJosonStr(flag);
		writeResponse(response, retStr);
	}
	
	private void delete(HttpServletRequest request, HttpServletResponse response) {
		logger.debug("[delete appRegister...]");
		boolean flag = true;
		JSONObject jo = JSONObject.fromObject(request.getParameter("para"));
		JSONArray idArr = (JSONArray)jo.opt("idArr");
		String idStr =StringUtil.buildIdsStr(idArr);
		String retStr = "";
		try {
			List<AppModel> l = appService.findByIds(idStr);
			for(AppModel app:l){
				app.setEntityStatus(Constants.STATUS_DEL);
				appService.update(app);
			}
		} catch (Exception e) {
			e.printStackTrace();
			flag = false;
		}
		retStr = ExtUtil.getJosonStr(flag);
		writeResponse(response, retStr);
	}
	
	private void active(HttpServletRequest request, HttpServletResponse response) {
		logger.debug("[active appRegister...]");
		boolean flag = true;
		JSONObject jo = JSONObject.fromObject(request.getParameter("para"));
		JSONArray idArr = (JSONArray)jo.opt("idArr");
		String idStr =StringUtil.buildIdsStr(idArr);
		String retStr = "";
		try {
			List<AppModel> l = appService.findByIds(idStr);
			for(AppModel app:l){
				app.setEntityStatus(Constants.STATUS_ACTIVE);
				appService.update(app);
			}
		} catch (Exception e) {
			e.printStackTrace();
			flag = false;
		}
		retStr = ExtUtil.getJosonStr(flag);
		writeResponse(response, retStr);
	}
	
	private void unactive(HttpServletRequest request, HttpServletResponse response) {
		logger.debug("[unactive appRegister...]");
		boolean flag = true;
		JSONObject jo = JSONObject.fromObject(request.getParameter("para"));
		JSONArray idArr = (JSONArray)jo.opt("idArr");
		String idStr =StringUtil.buildIdsStr(idArr);
		String retStr = "";
		try {
			List<AppModel> l = appService.findByIds(idStr);
			for(AppModel appModel:l){
				appModel.setEntityStatus(Constants.STATUS_UNACTIVE);
				appService.update(appModel);
			}
		} catch (Exception e) {
			e.printStackTrace();
			flag = false;
		}
		retStr = ExtUtil.getJosonStr(flag);
		writeResponse(response, retStr);
	}
	
	private AppModel buildAppRegister(HttpServletRequest request, String action) throws  ServiceException{
		
		AppModel appModel = null;
		
		JSONObject jo = JSONObject.fromObject(request.getParameter("para"));
		
		JSONObject formContent = jo.optJSONObject("formContent");
		JSONArray ja = jo.optJSONArray("propertyArr");
		
		String appId = formContent.optString("appId");
		String appCode = formContent.optString("appCode");
		String appName = formContent.optString("appName");
		String url = formContent.optString("url");
		String ssoType = formContent.optString("ssoType");
		String serverIp = formContent.optString("serverIp");
		String target = formContent.optString("target");
		String userFieldname = formContent.optString("userFieldname");
		String pwdFieldname = formContent.optString("pwdFieldname");
		String submitUrl = formContent.optString("submitUrl");
		String vendorName = formContent.optString("vendorName");
		String vendorAddress = formContent.optString("vendorAddress");
		String linkman = formContent.optString("linkman");
		String vendorTel = formContent.optString("vendorTel");
		String srvName = formContent.optString("srvName");
		String srvAddress = formContent.optString("srvAddress");
		String srvLinkman = formContent.optString("srvLinkman");
		String srvTel = formContent.optString("srvTel");
		String serverPort = formContent.optString("serverPort");
		String ver = formContent.optString("ver");
		
		String ExtFieldinfoStr = "";
		
		if(ja.size()!=0){
			ExtFieldinfoStr = Dom4jUtil.getXML(ja);
		}
		
		if("add".equals(action)){
			appModel = new AppModel();
		}else{
			appModel = appService.get(Long.parseLong(appId));
		}
		
		appModel.setAppCode(appCode);
		appModel.setAppName(appName);
		appModel.setCreateTs(new Date());
		appModel.setCreator(Constants.TEMP_CREATOR);
		appModel.setEntityStatus(Constants.STATUS_ACTIVE);
		appModel.setLastModifier(Constants.TEMP_CREATOR);
		appModel.setLinkman(linkman);
		appModel.setModifiedTs(new Date());
		appModel.setPwdFieldname(pwdFieldname);
		appModel.setRunStatus(Constants.RUN_STATUS_ABNORMAL);
		appModel.setServerIp(serverIp);
		appModel.setServerPort(Short.parseShort(serverPort));
		appModel.setSrvAddress(srvAddress);
		appModel.setSrvLinkman(srvLinkman);
		appModel.setSrvName(srvName);
		appModel.setSrvTel(srvTel);
		appModel.setSsoType(Short.parseShort(ssoType));
		appModel.setSubmitUrl(submitUrl);
		appModel.setTarget(Short.parseShort(target));
		appModel.setUrl(url);
		appModel.setUserFieldname(userFieldname);
		appModel.setUseStatus(Constants.USE_STATUS_ABNORMAL);
		appModel.setVendorAddress(vendorAddress);
		appModel.setVendorName(vendorName);
		appModel.setVendorTel(vendorTel);
		appModel.setVer(ver);
		
		if(ExtFieldinfoStr.length() != 0 ){
			appModel.setExtFieldinfo(ExtFieldinfoStr);
		}else{
			appModel.setExtFieldinfo("");
		}
		
		return appModel;
		
	}

}
